﻿using PmSoft;
using Modules.Project;
using PmSoft.Entity;
using PmSoft.Exceptions;

namespace ManagementApi.Mvc.ApplicationContexts;

/// <summary>
/// 需要选择项目的用户请求上下文
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class ProjectUserApplicationContext : ManagementApplicationContext
{
    public ProjectUserApplicationContext(IServiceProvider serviceProvider) : base(serviceProvider)
    {
    }

    private ProjectInfo? _projectInfo = null;

    /// <summary>
    /// 当前选择的项目
    /// </summary>
    public ProjectInfo CurrentProjectInfo
    {
        get
        {
            if (_projectInfo != null)
                return _projectInfo;

            if (CurrentUser is not IProjectUser projectUser)
                throw new BusinessException("当前非单项目管理用户");

            if (!projectUser.ProjectId.HasValue)
                throw new BusinessException("请选择项目");

            var projectService = GetService<ProjectService>();
            _projectInfo = projectService.GetProjectInfo(projectUser.ProjectId.Value);
            if (_projectInfo == null)
                throw new BusinessException("项目信息不存在");

            return (ProjectInfo)_projectInfo;
        }
    }
}
